from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field, validator

"""
pydantic在传值和赋值之间做了数据验证和转换的过程，能转就转，不能转就报错。
"""


class Address(BaseModel):
    street: str
    city: str
    state: str


class UserIn(BaseModel):
    id: int
    name: str = Field(pattern=r'^[a-zA-Z ]+$', min_length=1, max_length=50)  # 正则验证、长度验证
    age: int = Field(default=0, gt=0, lt=150)  # Field用于自定义验证范围 gt大于 lt小于
    email: str
    password: str
    create_time: Optional[datetime] = None
    delete_time: datetime = None
    friends: List[str] = []
    add: Address = None  # 嵌套模型

    @validator('email')
    def validate_email(cls, v):  # 自定义方法验证器
        if '@' not in v:
            raise ValueError('Invalid email')
        return v


class UserOut(BaseModel):
    id: int
    name: str = Field(pattern=r'^[a-zA-Z ]+$', min_length=1, max_length=50)  # 正则验证、长度验证
    age: int = Field(default=0, gt=0, lt=150)  # Field用于自定义验证范围 gt大于 lt小于
    email: str
    password: str
    create_time: Optional[datetime] = None
    delete_time: datetime = None
    friends: List[str] = []


test_data = {
    'id': "1",
    'name': 'John Doe',
    'email': 'johndoe@example.com',
    'password': 'password123',
    'create_time': '2021-01-01 12:00',
    'delete_time': datetime.now(),
    'friends': ['Jane Doe', 1]
}
# 展示验证数据并转换成对应类型
# user = UserIn(**test_data)
# print(user.id)
# print(type(user.id))
# print(user.name)
# print(user.email)
# print(user.password)
# print(repr(user.create_time))
# print(type(user.create_time))
# print(user.delete_time)
# print(user.friends)
#
# # 变成数据字典来使用
# print(user.dict())
#
# # 转为json类型：
# print(user.json())
